package org.jeecgframework.web.controller;

import java.io.InputStream;
import java.text.ParseException;
import java.util.*;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mybatis.ext.WiseCoreService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.service.CbsBackEquipmentDetailServiceI;
import org.jeecgframework.web.service.CbsReturnEquipmentServiceI;
import org.jeecgframework.web.service.WxCommonService;
import org.jeecgframework.web.service.impl.ZyInspectionPlanServiceImpl;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.util.*;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.OutputStream;
import java.io.IOException;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 返件主表信息
 * @date 2018-03-07 10:26:18
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsReturnEquipmentController")
public class CbsReturnEquipmentController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsReturnEquipmentController.class);

    @Autowired
    private CbsReturnEquipmentServiceI cbsReturnEquipmentService;
    @Autowired
    private CbsBackEquipmentDetailServiceI cbsBackEquipmentDetailService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private WiseCoreService wiseCoreService;
    @Autowired
    private WxCommonService wxCommonService;

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 返件主表信息列表 页面跳转(工程师)
     *
     * @return
     */
    @RequestMapping(params = "cbsReturnEquipmentGCS")
    public ModelAndView cbsReturnEquipmentGCS(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipmentList_GCS");
    }

    /**
     * 返件主表信息列表 页面跳转(工程师)待办
     *
     * @return
     */
    @RequestMapping(params = "cbsReturnEquipmentGCSTodo")
    public ModelAndView cbsReturnEquipmentGCSTodo(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipmentList_GCSTodo");
    }

    /**
     * 返件主表信息列表 页面跳转(物流)
     *
     * @return
     */
    @RequestMapping(params = "cbsReturnEquipmentWL")
    public ModelAndView cbsReturnEquipmentWL(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipmentList_WL");
    }

    /**
     * 返件主表信息列表 页面跳转(物流)待办
     *
     * @return
     */
    @RequestMapping(params = "cbsReturnEquipmentWLTodo")
    public ModelAndView cbsReturnEquipmentWLTodo(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipmentList_WLTodo");
    }

    /**
     * 返件主表信息列表 页面跳转(CSA)
     *
     * @return
     */
    @RequestMapping(params = "cbsReturnEquipmentCSA")
    public ModelAndView cbsReturnEquipmentCSA(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipmentList_CSA");
    }

    /**
     * 返件主表信息列表 页面跳转(CSA待办)
     *
     * @return
     */
    @RequestMapping(params = "cbsReturnEquipmentCSATodo")
    public ModelAndView cbsReturnEquipmentCSATodo(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipmentList_CSATodo");
    }

    /**
     * CSA返件详情页
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "detailesCSA")
    public ModelAndView detailesCSA(HttpServletRequest req) {
        String id = req.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
            req.setAttribute("id", id);
            /*关联信息*/
            CbsReturnEquipmentEntity cbsReturnEquipment = cbsReturnEquipmentService.getEntity(CbsReturnEquipmentEntity.class, id);
            if (StringUtil.isNotEmpty(cbsReturnEquipment)) {
                req.setAttribute("cbsReturnEquipmentPage", cbsReturnEquipment);

                //返件状态
                List<TSType> status = systemService.findHql("from TSType where TSTypegroup.typegroupcode='return_status' and typecode='" + cbsReturnEquipment.getStatus() + "'");
                if (status != null && status.size() > 0) {
                    req.setAttribute("status", status.get(0).getTypename());
                }
                /*取货联系人信息*/
                List<CbsDelinerEntity> cbsDelinerEntities = systemService.findByProperty(CbsDelinerEntity.class, "code", cbsReturnEquipment.getDeliverCode());
                if (cbsDelinerEntities.size() > 0) {
                    req.setAttribute("cbsDelinerEntities", cbsDelinerEntities.get(0));
                }
                //返件物流信息
//                String logisticsCode = cbsReturnEquipment.getLogisticsCode();//返件物流编号
//                String hql = "from TSDepart where org_code = '" + logisticsCode + "'";
//                TSDepart tsDepart = systemService.singleResult(hql);
//                req.setAttribute("tsDepart",tsDepart);

//                List<TSUserOrg> tsUserOrgs = systemService.findHql("from TSUserOrg where tsDepart.id = '" + tsDepart.getId() + "'");
//                if(tsUserOrgs.size()>0){
//                    TSUserOrg userOrg = tsUserOrgs.get(0);
//                    if(StringUtil.isNotEmpty(userOrg))
//                    req.setAttribute("tsUser", userOrg.getTsUser());
//                }

                //返件入库照片
                List<ZyFileLogEntity> backFileList = systemService.findHql("from ZyFileLogEntity where businessKey='" + id + "' and businessType='H'");
                req.setAttribute("backFileList", backFileList);
                //返件详情照片
                List<ZyFileLogEntity> detailFileList = systemService.findHql("from ZyFileLogEntity where businessType='E'");
//                List<ZyFileLogEntity> detailFileList = systemService.findHql("from ZyFileLogEntity where businessKey='" + id + "' and businessType='E'");
                req.setAttribute("detailFileList", detailFileList);

                if (cbsReturnEquipment.getSheng() != null) {
                    List<TSTerritory> shiList = systemService.findHql("from TSTerritory where territoryLevel=2 and TSTerritory.id='" + cbsReturnEquipment.getSheng().getId() + "'");
                    req.setAttribute("shiList", shiList);
                }
            }
            /*返件信息*/
            List<CbsReturnEquipmentDetailEntity> cbsReturnEquipmentDetailEntities = systemService.findByProperty(CbsReturnEquipmentDetailEntity.class, "returnEquipmentId.id", id);
            Map<String, Object> map = new HashMap<>();
            if (cbsReturnEquipmentDetailEntities.size() > 0) {
                req.setAttribute("cbsReturnEquipmentDetailEntities", cbsReturnEquipmentDetailEntities);
                //获取当前备件的对应的类型的备件号
                for (CbsReturnEquipmentDetailEntity ReturnEquipment : cbsReturnEquipmentDetailEntities) {
                    if (ReturnEquipment.getTypeId() != null) {
                        String hql = "from ZyEsItemEntity where type.id='" + ReturnEquipment.getTypeId().getId() + "'";
                        List<ZyEsItemEntity> equipmentItemList = systemService.findHql(hql);
                        map.put(ReturnEquipment.getId(), equipmentItemList);
                    }
                }
            }
            req.setAttribute("equipmentItemMap", map);
            /*入库信息*/
            List<CbsBackEquipmentDetailEntity> cbsBackEquipmentDetailEntities = systemService.findByProperty(CbsBackEquipmentDetailEntity.class, "returnEquipmentId.id", id);
            if (cbsBackEquipmentDetailEntities.size() > 0) {
                req.setAttribute("cbsBackEquipmentDetailEntities", cbsBackEquipmentDetailEntities);
            }

            //查询所有物流
            List<TSDepart> logList = systemService.findHql("from TSDepart where orgType='logistics' and logicDelete = '0'");
            req.setAttribute("logisticsList", logList);
            /*返件日志*/
            List<CbsHandleLogEntity> cbsHandleLogEntities = systemService.findHql("from CbsHandleLogEntity where logType=4 and businessId='" + id + "' ORDER BY createDate DESC");
            req.setAttribute("cbsHandleLogEntities", cbsHandleLogEntities);
        }

        //查询所有省
        List<TSTerritory> shengList = systemService.findHql("from TSTerritory where territoryLevel=1");
        req.setAttribute("shengList", shengList);
        //获取该返件单的省下的所有市
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipment_detailesCSA");
    }

    /**
     * 工程师返件详情页
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "detailesGCS")
    public ModelAndView detailesGCS(HttpServletRequest req) {
        String id = req.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
            req.setAttribute("id", id);
            /*关联信息*/
            CbsReturnEquipmentEntity cbsReturnEquipment = cbsReturnEquipmentService.getEntity(CbsReturnEquipmentEntity.class, id);
            if (StringUtil.isNotEmpty(cbsReturnEquipment)) {
                req.setAttribute("cbsReturnEquipmentPage", cbsReturnEquipment);

                //返件状态
                List<TSType> status = systemService.findHql("from TSType where TSTypegroup.typegroupcode='return_status' and typecode='" + cbsReturnEquipment.getStatus() + "'");
                if (status != null && status.size() > 0) {
                    req.setAttribute("status", status.get(0).getTypename());
                }
                /*取货联系人信息*/
                List<CbsDelinerEntity> cbsDelinerEntities = systemService.findByProperty(CbsDelinerEntity.class, "code", cbsReturnEquipment.getDeliverCode());
                if (cbsDelinerEntities.size() > 0) {
                    req.setAttribute("cbsDelinerEntities", cbsDelinerEntities.get(0));
                }

                //返件详情照片
                List<ZyFileLogEntity> detailFileList = systemService.findHql("from ZyFileLogEntity where businessType='E'");
//                List<ZyFileLogEntity> detailFileList = systemService.findHql("from ZyFileLogEntity where businessKey='" + id + "' and businessType='E'");
                req.setAttribute("detailFileList", detailFileList);

                //获取该返件单省下面的所有市
                if (cbsReturnEquipment.getSheng() != null) {
                    List<TSTerritory> shiList = systemService.findHql("from TSTerritory where territoryLevel=2 and TSTerritory.id='" + cbsReturnEquipment.getSheng().getId() + "'");
                    req.setAttribute("shiList", shiList);
                }
            }
            /*返件信息*/
            Map<String, Object> map = new HashMap<>();
            List<CbsReturnEquipmentDetailEntity> cbsReturnEquipmentDetailEntities = systemService.findByProperty(CbsReturnEquipmentDetailEntity.class, "returnEquipmentId.id", id);
            if (cbsReturnEquipmentDetailEntities.size() > 0) {
                req.setAttribute("cbsReturnEquipmentDetailEntities", cbsReturnEquipmentDetailEntities);
                //获取返件当前的备件类型对应的所有备件号
                for (CbsReturnEquipmentDetailEntity r : cbsReturnEquipmentDetailEntities) {
                    if (r.getTypeId() != null) {
                        List<ZyEsItemEntity> equipmentItemList = equipmentItemList = systemService.findHql("from ZyEsItemEntity where type.id='" + r.getTypeId().getId() + "'");
                        map.put(r.getId(), equipmentItemList);
                    }
                }
            }
            req.setAttribute("equipmentItemMap", map);

            /*返件日志*/
            List<CbsHandleLogEntity> cbsHandleLogEntities = systemService.findHql("from CbsHandleLogEntity where logType=4 and businessId='" + id + "' ORDER BY createDate DESC");
            req.setAttribute("cbsHandleLogEntities", cbsHandleLogEntities);
        }

        //查询所有省
        List<TSTerritory> shengList = systemService.findHql("from TSTerritory where territoryLevel=1");
        req.setAttribute("shengList", shengList);

        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipment_detailesGCS");
    }

    /**
     * 物流返件详情页
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "detailesWL")
    public ModelAndView detailesWL(HttpServletRequest req) {
        String id = req.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
            req.setAttribute("id", id);

            /*关联信息*/
            CbsReturnEquipmentEntity cbsReturnEquipment = cbsReturnEquipmentService.getEntity(CbsReturnEquipmentEntity.class, id);
            if (StringUtil.isNotEmpty(cbsReturnEquipment)) {
                req.setAttribute("cbsReturnEquipmentPage", cbsReturnEquipment);

                //返件状态
                List<TSType> status = systemService.findHql("from TSType where TSTypegroup.typegroupcode='return_status' and typecode='" + cbsReturnEquipment.getStatus() + "'");
                if (status != null && status.size() > 0) {
                    req.setAttribute("status", status.get(0).getTypename());
                }
                /*取货联系人信息*/
                List<CbsDelinerEntity> cbsDelinerEntities = systemService.findByProperty(CbsDelinerEntity.class, "code", cbsReturnEquipment.getDeliverCode());
                if (cbsDelinerEntities.size() > 0) {
                    req.setAttribute("cbsDelinerEntities", cbsDelinerEntities.get(0));
                    //获取当前城市所有的仓库
                    List<Map<String, Object>> cbsWarehouseList = null;
                    if (StringUtil.isNotEmpty(cbsReturnEquipment) && StringUtil.isNotEmpty(cbsReturnEquipment.getLogistics())) {
                        cbsWarehouseList = systemService.findForJdbc("SELECT\n" +
                                "\tw.id AS id,\n" +
                                "\tw.`name` AS `name`,\n" +
                                "\tw.user_name AS userName,\n" +
                                "\tw.phone AS phone,\n" +
                                "\tw.email AS email,\n" +
                                "\tw.logistics AS logistics\n" +
                                "FROM\n" +
                                "\tcbs_warehouse w\n" +
                                "WHERE\n" +
                                "\tw.is_close = '0'\n" +
                                "AND w.logistics = '" + cbsReturnEquipment.getLogistics() + "'");
                    }

                    req.setAttribute("wareList", cbsWarehouseList);
                }

                //返件入库照片
                List<ZyFileLogEntity> backFileList = systemService.findHql("from ZyFileLogEntity where businessKey='" + id + "' and businessType='H'");
                req.setAttribute("backFileList", backFileList);
                //返件详情照片
                List<ZyFileLogEntity> detailFileList = systemService.findHql("from ZyFileLogEntity where businessType='E'");
//                List<ZyFileLogEntity> detailFileList = systemService.findHql("from ZyFileLogEntity where businessKey='" + id + "' and businessType='E'");
                req.setAttribute("detailFileList", detailFileList);

                //所有开箱检查选项
                List<TSType> openTypeList = systemService.findHql("from TSType where TSTypegroup.typegroupcode='open_check'");
                req.setAttribute("openTypeList", openTypeList);

            }
            /*返件信息*/
            List<CbsReturnEquipmentDetailEntity> cbsReturnEquipmentDetailEntities = systemService.findByProperty(CbsReturnEquipmentDetailEntity.class, "returnEquipmentId.id", id);
            Map<String, Object> map = new HashMap<>();
            if (cbsReturnEquipmentDetailEntities.size() > 0) {
                req.setAttribute("cbsReturnEquipmentDetailEntities", cbsReturnEquipmentDetailEntities);
                for (CbsReturnEquipmentDetailEntity ReturnEquipment : cbsReturnEquipmentDetailEntities) {
                    if (ReturnEquipment.getItemId() != null) { //用于区分是否是未知备件，未知备件的情况下，itemid为空
                        String hql = "from ZyEsItemEntity where type.id='" + ReturnEquipment.getTypeId().getId() + "'";
                        List<ZyEsItemEntity> equipmentItemList = systemService.findHql(hql);
                        map.put(ReturnEquipment.getId(), equipmentItemList);
                    } else { //未知备件的情况下，直接输入框显示
                        List<ZyEsItemEntity> equipmentItemList = new ArrayList<>();
                        ZyEsItemEntity zyEsItemEntity = new ZyEsItemEntity();
                        zyEsItemEntity.setItem(ReturnEquipment.getItem());
                        equipmentItemList.add(zyEsItemEntity);
                        map.put(ReturnEquipment.getId(), equipmentItemList);
                    }
                }
            }
            req.setAttribute("equipmentItemMap", map);

            //获取所有返件库位
            List<TSType> kuweiList = systemService.findHql("from TSType where TSTypegroup.typegroupcode='return_kuwei'");
            req.setAttribute("kuweiList", kuweiList);


            //返件入库信息
            List<CbsBackEquipmentDetailEntity> cbsBackEquipmentDetailEntities = systemService.findByProperty(CbsBackEquipmentDetailEntity.class, "returnEquipmentId.id", id);
            if (cbsBackEquipmentDetailEntities.size() > 0) {
                req.setAttribute("cbsBackEquipmentDetailEntities", cbsBackEquipmentDetailEntities);
            }

            //返件操作日志
            List<CbsHandleLogEntity> cbsHandleLogEntities = systemService.findHql("from CbsHandleLogEntity where logType=4 and businessId='" + id + "' ORDER BY createDate DESC");
            req.setAttribute("cbsHandleLogEntities", cbsHandleLogEntities);
        }
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipment_detailesWL");
    }

    /**
     * easyui AJAX请求数据(工程师)
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */
    @RequestMapping(params = "datagridGCS")
    public void datagridGCS(CbsReturnEquipmentEntity cbsReturnEquipment, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        TSUser user = ResourceUtil.getSessionUserName();
        Map param = new HashMap<>();
        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                    }
                }
            }
        }
        //获取工程师id
        List<ZyEngineerEntity> egs = systemService.findByProperty(ZyEngineerEntity.class, "tsBaseUser.id", user.getId());
        if (egs.size() > 0) {
            param.put("user", egs.get(0).getId());
        }
        wiseCoreService.selectDataGrid("getdatagridGCS", param, dataGrid);

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * easyui AJAX请求数据(工程师)待办
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */
    @RequestMapping(params = "datagridGCSTodo")
    public void datagridGCSTodo(CbsReturnEquipmentEntity cbsReturnEquipment, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        TSUser user = ResourceUtil.getSessionUserName();
        Map param = new HashMap<>();
        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                    }
                }
            }
        }
        //获取工程师id
        List<ZyEngineerEntity> egs = systemService.findByProperty(ZyEngineerEntity.class, "tsBaseUser.id", user.getId());
        if (egs.size() > 0) {
            param.put("user", egs.get(0).getId());
        }
        wiseCoreService.selectDataGrid("getdatagridGCSTodo", param, dataGrid);

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * easyui AJAX请求数据(物流)
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "datagridWL")
    public void datagridWL(CbsReturnEquipmentEntity cbsReturnEquipment, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        TSUser user = ResourceUtil.getSessionUserName();
        Map param = new HashMap<>();
        //获取物流角色
        List<TSUserOrg> departOrgList = systemService.findHql("from TSUserOrg where tsUser.id = ?", user.getId());
        if (departOrgList.size() > 0) {
            TSDepart currentDepart = departOrgList.get(0).getTsDepart();
            param.put("orgCode", currentDepart.getDepartname());
        }
        // add start 190506 Amy 所有条件为空时，检索物流待处理的
        boolean flag = false; //页面查询条件是否为空
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
            if (   key.equals("code") || key.equals("status") || key.equals("so") ||
                    key.equals("cinemaName") || key.equals("shengName") ||
                    key.equals("shiName") || key.equals("delivercode") ||
                    key.equals("logisticscode") || key.equals("cr") ||
                    key.equals("pickupTime_begin") || key.equals("pickupTime_end") ||
                    key.equals("backTime_begin") || key.equals("backTime_end") ||
                    key.equals("noticeReturnTime_begin") || key.equals("noticeReturnTime_end")) {
                if (!StringUtil.isEmpty(parameterMap.get(key)[0])) {
                    flag = true;//页面 查询条件为空不做查询
                    break;
                }
            }
        }
        // add end 190506
        if (flag) {
	        for (Object key : request.getParameterMap().keySet()) {
	            if ((String[]) request.getParameterMap().get(key) != null) {
	                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
	                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
	                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
	                    }
	                }
	            }
	        }
        } else {
        	param.put("status",StaticValue.RETURN_STATUS_Log_Type_2);
        }
        wiseCoreService.selectDataGrid("getdatagridWL", param, dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * easyui AJAX请求数据(物流)待办
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "datagridWLTodo")
    public void datagridWLTodo(CbsReturnEquipmentEntity cbsReturnEquipment, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        TSUser user = ResourceUtil.getSessionUserName();
        Map param = new HashMap<>();
        //获取物流角色
        List<TSUserOrg> departOrgList = systemService.findHql("from TSUserOrg where tsUser.id = ?", user.getId());
        if (departOrgList.size() > 0) {
            TSDepart currentDepart = departOrgList.get(0).getTsDepart();
            param.put("orgCode", currentDepart.getDepartname());
        }
        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                    }
                }
            }
        }

        wiseCoreService.selectDataGrid("getdatagridWLTodo", param, dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * easyui AJAX请求数据(CSA)
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "datagridCSA")
    public void datagridCSA(CbsReturnEquipmentEntity cbsReturnEquipment, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        TSUser user = ResourceUtil.getSessionUserName();
        Map param = new HashMap<>();
        // add start 181204 Amy 所有条件为空时，检索待返件的
        boolean flag = false; //页面查询条件是否为空
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
            if (   key.equals("CODE") || key.equals("logistics") || key.equals("STATUS") ||
                    key.equals("delivercode") || key.equals("codes") ||
                    key.equals("cinemaName") || key.equals("logisticscode") ||
                    key.equals("shengName") || key.equals("shiName") ||
                    key.equals("cr") || key.equals("so") ||
                    key.equals("pickuptime_begin") || key.equals("pickuptime_end") ||
                    key.equals("noticeReturnTime_begin") || key.equals("noticeReturnTime_end")) {
                if (!StringUtil.isEmpty(parameterMap.get(key)[0])) {
                    flag = true;//页面 查询条件为空不做查询
                    break;
                }
            }
        }
        if (flag) {     
	        // add end 181204
	        for (Object key : request.getParameterMap().keySet()) {
	            if ((String[]) request.getParameterMap().get(key) != null) {
	                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
	                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
	                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
	                    }
	                }
	            }
	        }
	        if (StringUtil.isNotEmpty(user)) {
	            param.put("user", user.getId());
	        }
	        wiseCoreService.selectDataGrid("getdatagridCSA", param, dataGrid);
        } else {
            // add start 181204 Amy 所有条件为空时，检索待返件的
        	param.put("STATUS",StaticValue.RETURN_STATUS_Log_Type_1);
	        if (StringUtil.isNotEmpty(user)) {
	            param.put("user", user.getId());
	        }
	        wiseCoreService.selectDataGrid("getdatagridCSA", param, dataGrid);
	        // add end 181204
        }
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * easyui AJAX请求数据(CSA)待办
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "datagridCSATodo")
    public void datagridCSATodo(CbsReturnEquipmentEntity cbsReturnEquipment, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        TSUser user = ResourceUtil.getSessionUserName();
        Map param = new HashMap<>();
        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                    }
                }
            }
        }
        if (StringUtil.isNotEmpty(user)) {
            param.put("user", user.getId());
        }
        wiseCoreService.selectDataGrid("getdatagridCSATodo", param, dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * CSA修改返件物流
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "dopreservation")
    @ResponseBody
    public AjaxJson dopreservation(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        TSUser user = ResourceUtil.getSessionUserName();
        String returnId = request.getParameter("id");  //返件主表id
        String rd = request.getParameter("rd");  //返件详情id
        String list = request.getParameter("datalist");
        JSONArray jsonArray = JSONArray.fromObject(list);
        for (Object o : jsonArray) {
            JSONObject jso = JSONObject.fromObject(o);
            String id = jso.get("rd").toString();
            String fileId = jso.get("photoName").toString();
            ZyFileLogEntity photoFile = systemService.get(ZyFileLogEntity.class, fileId);
            if (StringUtil.isNotEmpty(id)) {
                /*返件详情表*/
                CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity = systemService.get(CbsReturnEquipmentDetailEntity.class, id);
                cbsReturnEquipmentDetailEntity.setReturnEquipmentStatus(jso.get("returnEquipmentStatus").toString()); //返件状态
                String typeId = jso.get("typeDesc").toString();
                if (typeId != null && !typeId.equals("")) {
                    ZyEquipmentTypeEntity type = systemService.get(ZyEquipmentTypeEntity.class, typeId);
                    if (type != null) {
                        cbsReturnEquipmentDetailEntity.setTypeId(type);
                        cbsReturnEquipmentDetailEntity.setTypeDes(type.getTypeDesc());
                    }
                }

                String itemId = jso.get("item").toString();
                String itemIn = jso.get("itemIn").toString();
                if (itemId != null && !itemId.equals("")) {
                    ZyEsItemEntity item = systemService.get(ZyEsItemEntity.class, itemId);
                    if (item != null) {
                        cbsReturnEquipmentDetailEntity.setItemId(item);
                        cbsReturnEquipmentDetailEntity.setItem(item.getItem());
                    }
                } else {
                    cbsReturnEquipmentDetailEntity.setItemId(null);
                    cbsReturnEquipmentDetailEntity.setItem(itemIn);
                }
                cbsReturnEquipmentDetailEntity.setEquipmentErcode(jso.get("equipmentErcode").toString());
                cbsReturnEquipmentDetailEntity.setSn(jso.get("sn").toString());
                cbsReturnEquipmentDetailEntity.setMemo(jso.get("memo").toString());
                if (photoFile != null) {
                    cbsReturnEquipmentDetailEntity.setPhotoName(photoFile.getOldFileName());
                    cbsReturnEquipmentDetailEntity.setFilePath(photoFile.getFilePath());
                }
                systemService.saveOrUpdate(cbsReturnEquipmentDetailEntity);

            }
        }
        if (StringUtil.isNotEmpty(returnId)) {
            CbsReturnEquipmentEntity cbsReturnEquipmentEntity = systemService.get(CbsReturnEquipmentEntity.class, returnId);
            String shengId = request.getParameter("sheng");
            String shiId = request.getParameter("shi");
            if (StringUtil.isNotEmpty(shengId)) {
                TSTerritory sheng = systemService.get(TSTerritory.class, shengId);
                if (sheng != null) {
                    cbsReturnEquipmentEntity.setSheng(sheng);
                }
            }
            if (StringUtil.isNotEmpty(shiId)) {
                TSTerritory shi = systemService.get(TSTerritory.class, shiId);
                if (shi != null) {
                    cbsReturnEquipmentEntity.setShi(shi);
                }
            }
            cbsReturnEquipmentEntity.setName(request.getParameter("name"));
            cbsReturnEquipmentEntity.setPhone(request.getParameter("phone"));
            cbsReturnEquipmentEntity.setAddress(request.getParameter("address"));
            cbsReturnEquipmentEntity.setCinemaName(request.getParameter("cinemaName"));
            cbsReturnEquipmentEntity.setLogistics(request.getParameter("logistics"));
            systemService.saveOrUpdate(cbsReturnEquipmentEntity);
        }

        return ajaxJson;
    }


    /**
     * CSA通知返件
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params = "doReturnEquipment")
    @ResponseBody
    public AjaxJson doReturnEquipment(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        boolean flag = true;
        String message = "返件成功！";
        String returnId = request.getParameter("id");  //返件主表id
        String list = request.getParameter("datalist");

        if (StringUtil.isNotEmpty(returnId)) {
            CbsReturnEquipmentEntity cbsReturnEquipmentEntity = systemService.get(CbsReturnEquipmentEntity.class, returnId);
            if (cbsReturnEquipmentEntity.getStatus().equals(StaticValue.RETURN_STATUS_Log_Type_1)) {

                cbsReturnEquipmentEntity.setStatus(StaticValue.RETURN_STATUS_Log_Type_2);  //返件中
                cbsReturnEquipmentEntity.setName(request.getParameter("name"));
                cbsReturnEquipmentEntity.setPhone(request.getParameter("phone"));
                cbsReturnEquipmentEntity.setAddress(request.getParameter("address"));
                cbsReturnEquipmentEntity.setCinemaName(request.getParameter("cinemaName"));
                cbsReturnEquipmentEntity.setNoticeReturnTime(new Date()); //返件时间
                cbsReturnEquipmentEntity.setLogistics(request.getParameter("logistics"));
                String shengId = request.getParameter("sheng");
                String shiId = request.getParameter("shi");
                if (StringUtil.isNotEmpty(shengId)) {
                    TSTerritory sheng = systemService.get(TSTerritory.class, shengId);
                    if (sheng != null) {
                        cbsReturnEquipmentEntity.setSheng(sheng);
                    }
                }
                if (StringUtil.isNotEmpty(shiId)) {
                    TSTerritory shi = systemService.get(TSTerritory.class, shiId);
                    if (shi != null) {
                        cbsReturnEquipmentEntity.setShi(shi);
                    }
                }
                cbsReturnEquipmentService.saveOrUpdate(cbsReturnEquipmentEntity);
                ajaxJson.setMsg("通知返件成功！");
                //记录操作日志
                TSUser user = ResourceUtil.getSessionUserName();
                CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                cbsHandleLogEntity.setBusinessId(cbsReturnEquipmentEntity.getId());
                cbsHandleLogEntity.setLogType(4);
                cbsHandleLogEntity.setDescription("通知返件");
                cbsHandleLogEntity.setCreateName(user.getRealName());
                cbsHandleLogEntity.setCreateBy(user.getUserName());
                systemService.saveOrUpdate(cbsHandleLogEntity);

                /*通知返件后24小时（该时限可人为设置）后该返件任务状态依然为“返件中”，短信提醒物流商务联系人*/
                if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity)) {
                    returnEquimentStatus(cbsReturnEquipmentEntity.getId());
                }

                //获取影院名称
                String cinemaName = "";
                List<CbsDelinerEntity> CbsDelinerEntitys = systemService.findHql("from CbsDelinerEntity where code = '" + cbsReturnEquipmentEntity.getDeliverCode() + "'");
                if (CbsDelinerEntitys.size() > 0) {
                    cinemaName = CbsDelinerEntitys.get(0).getCinemaName();
                }

                /*CSA通知返件后邮件和短信以及APP信息  给物流联系人*/
                if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity)) {
                    String logistics = cbsReturnEquipmentEntity.getLogistics();  //物流
                    if (StringUtil.isNotEmpty(logistics)) {
                        String hql = "from TSDepart where departname = '" + logistics + "' and orgType='" + StaticValue.CBS_WL_ROLE_CODE + "'";
                        TSDepart tsDepart = systemService.singleResult(hql);
                        List<ZyContactsEntity> zyContactsEntities = systemService.findHql("from ZyContactsEntity where belongOrg.id = '" + tsDepart.getId() + "'");
                        if (zyContactsEntities != null && zyContactsEntities.size() > 0) {
                            for (ZyContactsEntity zyContactsEntity : zyContactsEntities) {
                                //18/5/17   修改取物流联系人为在职的物流联系人
                                if (zyContactsEntity.getState().equals(StaticValue.DIC_ENGINEER_STATE_ONJOB)) {
                                    TSUser tsUser = ResourceUtil.getSessionUserName(); // 当前人id
                                    /*邮件*/
                                    ZyEmailEntity eMail = new ZyEmailEntity();
                                    SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                                    String s = "返件通知：<" + cbsReturnEquipmentEntity.getCode() + ">-<" + cbsReturnEquipmentEntity.getCrCode() + ">-<" + cinemaName + ">-<" + cbsReturnEquipmentEntity.getSoCode() + ">-" + sdf.format(new Date()) + "";
                                    eMail.setEmailSubject(s);
                                    eMail.setEmailReceiver(zyContactsEntity.getEmail());
                                    Map<String, Object> paraMap1 = new HashMap<String, Object>();
                                    paraMap1.put("code", cbsReturnEquipmentEntity.getCode());
                                    paraMap1.put("zyContactsName", tsUser.getRealName());
                                    paraMap1.put("phone", tsUser.getMobilePhone());
                                    SendMailUtil.sendFtlMail(eMail, "mail_back_service.ftl", paraMap1, systemService);

                                    /*短信*/
                                    Map<String, Object> paraMap = new HashMap<String, Object>();
                                    paraMap.put("code", cbsReturnEquipmentEntity.getCode());
                                    paraMap.put("zyContactsName", tsUser.getRealName());
                                    paraMap.put("phone", tsUser.getMobilePhone());
                                    SendMessage.sendSMSFTL(zyContactsEntity.getCellphone1(), "message_back_service.ftl", paraMap, systemService);
                                }
                            }
                        }
                    }
                }

                JSONArray jsonArray = JSONArray.fromObject(list);
                for (Object o : jsonArray) {
                    JSONObject jso = JSONObject.fromObject(o);
                    String id = jso.get("rd").toString();
                    String fileId = jso.get("photoName").toString();
                    ZyFileLogEntity photoFile = systemService.get(ZyFileLogEntity.class, fileId);
                    if (StringUtil.isNotEmpty(id)) {
                        /*返件详情表*/
                        CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity = systemService.get(CbsReturnEquipmentDetailEntity.class, id);
                        cbsReturnEquipmentDetailEntity.setReturnEquipmentStatus(jso.get("returnEquipmentStatus").toString()); //返件状态
                        String typeId = jso.get("typeDesc").toString();
                        if (typeId != null && !typeId.equals("")) {
                            ZyEquipmentTypeEntity type = systemService.get(ZyEquipmentTypeEntity.class, typeId);
                            if (type != null) {
                                cbsReturnEquipmentDetailEntity.setTypeId(type);
                                cbsReturnEquipmentDetailEntity.setTypeDes(type.getTypeDesc());
                            }
                        }

                        String itemId = jso.get("item").toString();
                        String itemIn = jso.get("itemIn").toString();
                        if (itemId != null && !itemId.equals("")) {
                            ZyEsItemEntity item = systemService.get(ZyEsItemEntity.class, itemId);
                            if (item != null) {
                                cbsReturnEquipmentDetailEntity.setItemId(item);
                                cbsReturnEquipmentDetailEntity.setItem(item.getItem());
                            }
                        } else {
                            cbsReturnEquipmentDetailEntity.setItemId(null);
                            cbsReturnEquipmentDetailEntity.setItem(itemIn);
                        }
                        cbsReturnEquipmentDetailEntity.setEquipmentErcode(jso.get("equipmentErcode").toString());
                        cbsReturnEquipmentDetailEntity.setSn(jso.get("sn").toString());
                        cbsReturnEquipmentDetailEntity.setMemo(jso.get("memo").toString());
                        if (photoFile != null) {
                            cbsReturnEquipmentDetailEntity.setPhotoName(photoFile.getOldFileName());
                            cbsReturnEquipmentDetailEntity.setFilePath(photoFile.getFilePath());
                        }
                        systemService.saveOrUpdate(cbsReturnEquipmentDetailEntity);
                    }
                }

            } else {
                message = "返件状态不正确，请刷新后再操作";
                flag = false;
            }
        } else {
            message = "返件信息不正确！";
            flag = false;
        }
        ajaxJson.setMsg(message);
        ajaxJson.setSuccess(flag);
        return ajaxJson;
    }

    /**
     * 通知返件后24小时（该时限可人为设置）后该返件任务状态依然为“返件中”，短信提醒物流联系人和CSA
     *
     * @param id 返件主表id
     */
    public void returnEquimentStatus(final String id) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                CbsReturnEquipmentEntity cbsReturnEquipmentEntity = systemService.get(CbsReturnEquipmentEntity.class, id);
                if (cbsReturnEquipmentEntity.getStatus().equals(StaticValue.RETURN_STATUS_Log_Type_2)) {
                    //获取影院名称
                    String cinemaName = "";
                    List<CbsDelinerEntity> CbsDelinerEntitys = systemService.findHql("from CbsDelinerEntity where code = '" + cbsReturnEquipmentEntity.getDeliverCode() + "'");
                    if (CbsDelinerEntitys.size() > 0) {
                        cinemaName = CbsDelinerEntitys.get(0).getCinemaName();
                    }

                    String logistics = cbsReturnEquipmentEntity.getLogistics();  //物流单号
                    if (StringUtil.isNotEmpty(logistics)) {
                        String hql = "from TSDepart where departname = '" + logistics + "' and orgType='logistics'";
                        TSDepart tsDepart = systemService.singleResult(hql);
                        List<ZyContactsEntity> zyContactsEntities = systemService.findHql("from ZyContactsEntity where belongOrg.id = '" + tsDepart.getId() + "'");
                        if (zyContactsEntities != null && zyContactsEntities.size() > 0) {
                            for (ZyContactsEntity zyContactsEntity : zyContactsEntities) {
                                //18/5/17   修改取物流联系人为在职的物流联系人
                                if (zyContactsEntity.getState().equals(StaticValue.DIC_ENGINEER_STATE_ONJOB)) {
                                    //物流联系人
                                    /*邮件*/
                                    ZyEmailEntity eMail = new ZyEmailEntity();
                                    SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                                    String s = "返件超时提醒通知：<" + cbsReturnEquipmentEntity.getCode() + ">-<" + cbsReturnEquipmentEntity.getCrCode() + ">-<" + cinemaName + ">-<" + cbsReturnEquipmentEntity.getSoCode() + ">-" + sdf.format(new Date()) + "";
                                    eMail.setEmailSubject(s);
                                    eMail.setEmailReceiver(zyContactsEntity.getEmail());
                                    Map<String, Object> paraMap1 = new HashMap<String, Object>();
                                    paraMap1.put("code", cbsReturnEquipmentEntity.getCode());
                                    SendMailUtil.sendFtlMail(eMail, "mail_back_agin_service.ftl", paraMap1, systemService);
                                    /*短信*/
                                    if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity.getCode())) {
                                        SendMessage.sendSMSFTL(zyContactsEntity.getCellphone1(), "message_back_agin_service.ftl", paraMap1, systemService);
                                    }

                                    /*所有CSA*/
                                    List<Map<String, String>> list = getAllCSAUser();
                                    if (list.size() > 0 && StringUtil.isNotEmpty(cbsReturnEquipmentEntity.getCode())) {
                                        for (Map<String, String> stringStringMap : list) {
                                            ZyEmailEntity eMail1 = new ZyEmailEntity();
                                            eMail1.setEmailSubject(s);
                                            eMail1.setEmailReceiver(stringStringMap.get("email"));
                                            SendMailUtil.sendFtlMail(eMail1, "mail_back_agin_service.ftl", paraMap1, systemService);
                                            if (StringUtil.isNotEmpty(stringStringMap.get("phone"))) {
                                                SendMessage.sendSMSFTL(stringStringMap.get("phone"), "message_back_agin_service.ftl", paraMap1, systemService);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }, StaticValue.returnEquimentTiem);
    }

    //获取所有的CSA角色 联系电话和邮箱
    public List<Map<String, String>> getAllCSAUser() {
        List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
        List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSRole.roleCode='" + StaticValue.RULE_CODE_BARCO_CSA_ZB + "'");
        if (tsRoleUserList != null) {
            for (TSRoleUser ru : tsRoleUserList) {
                if (StringUtil.isNotEmpty(ru.getTSUser()) && ru.getTSUser().getStatus().equals(Globals.User_Normal)) {  //18/5/17 增加条件，查询用户状态是正常登陆的用户
                    /*CSA*/
                    Map<String, String> map = new HashMap();
                    map.put("phone", ru.getTSUser().getMobilePhone());
                    map.put("email", ru.getTSUser().getEmail());
                    mapList.add(map);
                }
            }
        }
        return mapList;
    }

    /**
     * 物流返件入库信息填写
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "doReturnEquipmentWL")
    public AjaxJson doReturnEquipmentWL(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        boolean flag = true;
        String mainId = request.getParameter("mainId"); //主表id
        String unqualified = request.getParameter("unqualified"); //主表id
        String unqualifiedMemo = request.getParameter("unqualifiedMemo"); //主表id
        String code = request.getParameter("code"); //主表id
        CbsReturnEquipmentEntity cbsReturnEquipmentEntity = null;
        /*返件主表*/
        if (StringUtil.isNotEmpty(mainId)) {
            cbsReturnEquipmentEntity = systemService.get(CbsReturnEquipmentEntity.class, mainId);
            cbsReturnEquipmentEntity.setUnqualified(unqualified); //未达标原因
            cbsReturnEquipmentEntity.setUnqualifiedMemo(unqualifiedMemo);  //未达标备注
            cbsReturnEquipmentEntity.setStatus(StaticValue.RETURN_STATUS_Log_Type_4);
            cbsReturnEquipmentEntity.setInwarehouseTime(new Date());
            cbsReturnEquipmentEntity.setLogisticsCode(code);
            cbsReturnEquipmentService.saveOrUpdate(cbsReturnEquipmentEntity);

            //记录操作日志
            TSUser user = ResourceUtil.getSessionUserName();
            CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
            cbsHandleLogEntity.setBusinessId(cbsReturnEquipmentEntity.getId());
            cbsHandleLogEntity.setLogType(4);
            cbsHandleLogEntity.setDescription("返件入库");
            cbsHandleLogEntity.setCreateName(user.getRealName());
            cbsHandleLogEntity.setCreateBy(user.getUserName());
            systemService.saveOrUpdate(cbsHandleLogEntity);

        }
        String list = request.getParameter("datalist");
        JSONArray jsonArray = JSONArray.fromObject(list);
        for (Object o : jsonArray) {
            JSONObject jso = JSONObject.fromObject(o);
            String id = jso.get("id").toString(); //详情id
            String typeDesc = jso.get("typeDesc").toString();
            String item = jso.get("item").toString();
            String itemIn = jso.get("itemIn").toString();  //如果是未知备件，获取填写的备件号
            ZyEsItemEntity itemEntity = null;
            if (StringUtil.isNotEmpty(item)) {
                itemEntity = systemService.get(ZyEsItemEntity.class, item);
            }
            String matterNum = jso.get("matterNum").toString();
            String sn = jso.get("sn").toString();
            String verCode = jso.get("verCode").toString();
            String equipmentErcode = jso.get("equipmentErcode").toString();
            String photoNameBack = jso.get("photoNameBack").toString(); //附件id
            String memo = jso.get("memo").toString();
            String warehousePosition = jso.get("warehousePosition").toString();
            String wareId = jso.get("warehouse").toString();
            String openCheck = jso.get("openCheck").toString();
            CbsWarehouseEntity warehouse = systemService.get(CbsWarehouseEntity.class, wareId);

            if (StringUtil.isNotEmpty(id)) {
                //检查入库返件序列号和工程师填写的返件序列号是否一致
                CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity = systemService.get(CbsReturnEquipmentDetailEntity.class, id);
                if (StringUtil.isNotEmpty(cbsReturnEquipmentDetailEntity)) {
                    if (StringUtil.isNotEmpty(cbsReturnEquipmentDetailEntity.getSn())) {
                        boolean flags = false;
                        if (StringUtil.isNotEmpty(cbsReturnEquipmentDetailEntity.getItemId()) && cbsReturnEquipmentDetailEntity.getItemId().getIsTrack().equals("1") && !cbsReturnEquipmentDetailEntity.getSn().equals(sn)) {
                            flags = true;
                        } else { //判断未知备件的，备件号是否与工程师填写的序列号一致
                            List<Map<String, Object>> zyEsItemList = systemService.findForJdbc("select * from zy_es_item where item = '" + cbsReturnEquipmentDetailEntity.getItem() + "'");
                            if (zyEsItemList.size() > 0) {
                                if (StringUtil.isNotEmpty(zyEsItemList.get(0).get("is_track")) && zyEsItemList.get(0).get("is_track").equals("1") && !cbsReturnEquipmentDetailEntity.getSn().equals(sn)) {
                                    flags = true;
                                }
                            }
                        }

                        if (flags) {
                            //添加异常记录
                            CbsBackErrorLogEntity cbsBackErrorLogEntity = new CbsBackErrorLogEntity();
                            cbsBackErrorLogEntity.setDescription("入库和工程师返件序列号不一致");
                            cbsBackErrorLogEntity.setCbsReturnId(cbsReturnEquipmentDetailEntity.getReturnEquipmentId()); //返件id
                            cbsBackErrorLogEntity.setCbsReturnDetailId(cbsReturnEquipmentDetailEntity); //返件明细Id
                            cbsBackErrorLogEntity.setIsClose(1);
                            systemService.saveOrUpdate(cbsBackErrorLogEntity);
                            //添加返件操作日志
                            CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                            cbsHandleLogEntity.setBusinessId(cbsReturnEquipmentDetailEntity.getReturnEquipmentId().getId());
                            cbsHandleLogEntity.setDescription("入库和工程师返件序列号不一致");
                            cbsHandleLogEntity.setLogType(4);
                            systemService.saveOrUpdate(cbsHandleLogEntity);

                            //获取影院名称
                            String cinemaName = "";
                            List<CbsDelinerEntity> CbsDelinerEntitys = systemService.findHql("from CbsDelinerEntity where code = '" + cbsReturnEquipmentEntity.getDeliverCode() + "'");
                            if (CbsDelinerEntitys.size() > 0) {
                                cinemaName = CbsDelinerEntitys.get(0).getCinemaName();
                            }

                            SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                            String s = "返件异常提醒：<" + cbsReturnEquipmentEntity.getCode() + ">-<" + cbsReturnEquipmentEntity.getCrCode() + ">-<" + cinemaName + ">-<" + cbsReturnEquipmentEntity.getSoCode() + ">-" + sdf.format(new Date()) + "";
                            Map<String, Object> paraMap1 = new HashMap<String, Object>();
                            paraMap1.put("code", cbsReturnEquipmentEntity.getCode());
                            /*所有CSA*/
                            List<Map<String, String>> listMap = getAllCSAUser();
                            if (listMap.size() > 0) {
                                for (Map<String, String> stringStringMap : listMap) {
                                    ZyEmailEntity eMail1 = new ZyEmailEntity();
                                    eMail1.setEmailSubject(s);
                                    eMail1.setEmailReceiver(stringStringMap.get("email"));
                                    SendMailUtil.sendFtlMail(eMail1, "mail_back_error_service.ftl", paraMap1, systemService);
                                }
                            }
                        }
                    } else {
                        boolean flags = false;
                        if (StringUtil.isNotEmpty(cbsReturnEquipmentDetailEntity.getItemId()) && cbsReturnEquipmentDetailEntity.getItemId().getIsTrack().equals("1") && !sn.equals("")) {
                            flags = true;
                        } else { //判断未知备件的，备件号是否与工程师填写的序列号一致
                            List<Map<String, Object>> zyEsItemList = systemService.findForJdbc("select * from zy_es_item where item = '" + cbsReturnEquipmentDetailEntity.getItem() + "'");
                            if (zyEsItemList.size() > 0) {
                                if (StringUtil.isNotEmpty(zyEsItemList.get(0).get("is_track")) && zyEsItemList.get(0).get("is_track").equals("1") && !sn.equals("")) {
                                    flags = true;
                                }
                            }
                        }

                        if (flags) {
                            //添加异常记录
                            CbsBackErrorLogEntity cbsBackErrorLogEntity = new CbsBackErrorLogEntity();
                            cbsBackErrorLogEntity.setDescription("入库和工程师返件序列号不一致");
                            cbsBackErrorLogEntity.setCbsReturnId(cbsReturnEquipmentDetailEntity.getReturnEquipmentId()); //返件id
                            cbsBackErrorLogEntity.setCbsReturnDetailId(cbsReturnEquipmentDetailEntity); //返件明细Id
                            cbsBackErrorLogEntity.setIsClose(1);
                            systemService.saveOrUpdate(cbsBackErrorLogEntity);
                            //添加返件操作日志
                            CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                            cbsHandleLogEntity.setBusinessId(cbsReturnEquipmentDetailEntity.getReturnEquipmentId().getId());
                            cbsHandleLogEntity.setDescription("入库和工程师返件序列号不一致");
                            cbsHandleLogEntity.setLogType(4);
                            systemService.saveOrUpdate(cbsHandleLogEntity);

                            //获取影院名称
                            String cinemaName = "";
                            List<CbsDelinerEntity> CbsDelinerEntitys = systemService.findHql("from CbsDelinerEntity where code = '" + cbsReturnEquipmentEntity.getDeliverCode() + "'");
                            if (CbsDelinerEntitys.size() > 0) {
                                cinemaName = CbsDelinerEntitys.get(0).getCinemaName();
                            }

                            SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                            String s = "返件异常提醒：<" + cbsReturnEquipmentEntity.getCode() + ">-<" + cbsReturnEquipmentEntity.getCrCode() + ">-<" + cinemaName + ">-<" + cbsReturnEquipmentEntity.getSoCode() + ">-" + sdf.format(new Date()) + "";
                            Map<String, Object> paraMap1 = new HashMap<String, Object>();
                            paraMap1.put("code", cbsReturnEquipmentEntity.getCode());
                            /*所有CSA*/
                            List<Map<String, String>> listMap = getAllCSAUser();
                            if (listMap.size() > 0) {
                                for (Map<String, String> stringStringMap : listMap) {
                                    ZyEmailEntity eMail1 = new ZyEmailEntity();
                                    eMail1.setEmailSubject(s);
                                    eMail1.setEmailReceiver(stringStringMap.get("email"));
                                    SendMailUtil.sendFtlMail(eMail1, "mail_back_error_service.ftl", paraMap1, systemService);
                                }
                            }
                        }
                    }
                }
            }

            if (equipmentErcode != null) {
                /*检查入库备件二维码和工程师填写的二维码是否一致*/
                CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity = systemService.get(CbsReturnEquipmentDetailEntity.class, id);
                if (StringUtil.isNotEmpty(cbsReturnEquipmentDetailEntity)) {
                    if (StringUtil.isNotEmpty(cbsReturnEquipmentDetailEntity.getEquipmentErcode())) {
                        boolean flags = false;
                        if (StringUtil.isNotEmpty(cbsReturnEquipmentDetailEntity.getItemId()) && cbsReturnEquipmentDetailEntity.getItemId().getIsTrack().equals("1") && !cbsReturnEquipmentDetailEntity.getEquipmentErcode().equals(equipmentErcode)) {
                            flags = true;
                        } else { //判断未知备件的，备件号是否与工程师填写的序列号一致
                            List<Map<String, Object>> zyEsItemList = systemService.findForJdbc("select * from zy_es_item where item = '" + cbsReturnEquipmentDetailEntity.getItem() + "'");
                            if (zyEsItemList.size() > 0) {
                                if (StringUtil.isNotEmpty(zyEsItemList.get(0).get("is_track")) && zyEsItemList.get(0).get("is_track").equals("1") && !cbsReturnEquipmentDetailEntity.getEquipmentErcode().equals(equipmentErcode)) {
                                    flags = true;
                                }
                            }
                        }
                        if (flags) {
                            //添加异常记录
                            CbsBackErrorLogEntity cbsBackErrorLogEntity = new CbsBackErrorLogEntity();
                            cbsBackErrorLogEntity.setDescription("入库和工程师返件二维码不一致");
                            cbsBackErrorLogEntity.setCbsReturnId(cbsReturnEquipmentDetailEntity.getReturnEquipmentId()); //返件id
                            cbsBackErrorLogEntity.setCbsReturnDetailId(cbsReturnEquipmentDetailEntity); //返件明细Id
                            cbsBackErrorLogEntity.setIsClose(1);
                            systemService.saveOrUpdate(cbsBackErrorLogEntity);

                            CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                            cbsHandleLogEntity.setDescription("入库和工程师返件二维码不一致");
                            cbsHandleLogEntity.setLogType(4);
                            systemService.saveOrUpdate(cbsHandleLogEntity);
                            /*并自动向CSA发送提醒邮件。同时提示物流需上传入库备件序列号照片。*/
//                        SendMailUtil.sendeMail("906189714@qq.com", "返件异常", "入库和工程师返件二维码不一致", systemService);
                        }

                    } else {
                        boolean flags = false;
                        if (StringUtil.isNotEmpty(cbsReturnEquipmentDetailEntity.getItemId()) && cbsReturnEquipmentDetailEntity.getItemId().getIsTrack().equals("1") && !equipmentErcode.equals("")) {
                            flags = true;
                        } else { //判断未知备件的，备件号是否与工程师填写的序列号一致
                            List<Map<String, Object>> zyEsItemList = systemService.findForJdbc("select * from zy_es_item where item = '" + cbsReturnEquipmentDetailEntity.getItem() + "'");
                            if (zyEsItemList.size() > 0) {
                                if (StringUtil.isNotEmpty(zyEsItemList.get(0).get("is_track")) && zyEsItemList.get(0).get("is_track").equals("1") && !equipmentErcode.equals("")) {
                                    flags = true;
                                }
                            }
                        }

                        if (flags) {
                            //添加异常记录
                            CbsBackErrorLogEntity cbsBackErrorLogEntity = new CbsBackErrorLogEntity();
                            cbsBackErrorLogEntity.setDescription("入库和工程师返件二维码不一致");
                            cbsBackErrorLogEntity.setCbsReturnId(cbsReturnEquipmentDetailEntity.getReturnEquipmentId()); //返件id
                            cbsBackErrorLogEntity.setCbsReturnDetailId(cbsReturnEquipmentDetailEntity); //返件明细Id
                            cbsBackErrorLogEntity.setIsClose(1);
                            systemService.saveOrUpdate(cbsBackErrorLogEntity);

                            CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                            cbsHandleLogEntity.setDescription("入库和工程师返件二维码不一致");
                            cbsHandleLogEntity.setLogType(4);
                            systemService.saveOrUpdate(cbsHandleLogEntity);
                            /*并自动向CSA发送提醒邮件。同时提示物流需上传入库备件序列号照片。*/
//                        SendMailUtil.sendeMail("906189714@qq.com", "返件异常", "入库和工程师返件二维码不一致", systemService);
                        }
                    }
                }
            }

            if (flag) {
                CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity = null;
                //返件明细
                if (StringUtil.isNotEmpty(id)) {
                    cbsReturnEquipmentDetailEntity = systemService.get(CbsReturnEquipmentDetailEntity.class, id);
                }

                CbsBackEquipmentDetailEntity cbsBackEquipmentDetailEntity = null;

                List<CbsBackEquipmentDetailEntity> cbsBackEquipmentDetailEntityList = systemService.findByProperty(CbsBackEquipmentDetailEntity.class, "returnEquipmentDetailId.id", id);
                if (cbsBackEquipmentDetailEntityList.size() > 0) {
                    cbsBackEquipmentDetailEntity = cbsBackEquipmentDetailEntityList.get(0);
                    cbsBackEquipmentDetailEntity.setReturnEquipmentId(cbsReturnEquipmentEntity);
                    cbsBackEquipmentDetailEntity.setReturnEquipmentDetailId(cbsReturnEquipmentDetailEntity);
                    cbsBackEquipmentDetailEntity.setVerCode(verCode);
                    cbsBackEquipmentDetailEntity.setWarehouseId(warehouse);
                    cbsBackEquipmentDetailEntity.setWarehousePosition(warehousePosition);
                    cbsBackEquipmentDetailEntity.setSn(sn);
                    if (itemEntity != null) {
                        cbsBackEquipmentDetailEntity.setItemId(itemEntity);
                        cbsBackEquipmentDetailEntity.setItem(itemEntity.getItem());
                    } else {
                        cbsBackEquipmentDetailEntity.setItemId(null);
                        cbsBackEquipmentDetailEntity.setItem(itemIn);
                    }
                    cbsBackEquipmentDetailEntity.setEquipmentErcode(equipmentErcode);
                    cbsBackEquipmentDetailEntity.setMemo(memo);
                    cbsBackEquipmentDetailEntity.setMatterNum(matterNum);
                    cbsBackEquipmentDetailEntity.setOpenCheck(openCheck);
                    systemService.saveOrUpdate(cbsBackEquipmentDetailEntity);
                    //开箱检查创建异常记录
                    if (StringUtil.isNotEmpty(openCheck) && !openCheck.equals(StaticValue.open_zc)) {
                        CbsBackErrorLogEntity cbsBackErrorLogEntity = new CbsBackErrorLogEntity();
                        cbsBackErrorLogEntity.setDescription("入库开箱检查异常");
                        cbsBackErrorLogEntity.setCbsReturnId(cbsReturnEquipmentDetailEntity.getReturnEquipmentId()); //返件id
                        cbsBackErrorLogEntity.setCbsReturnDetailId(cbsReturnEquipmentDetailEntity); //返件明细Id
                        cbsBackErrorLogEntity.setIsClose(1);
                        systemService.saveOrUpdate(cbsBackErrorLogEntity);
                    }

                } else {
                    cbsBackEquipmentDetailEntity = new CbsBackEquipmentDetailEntity();
                    cbsBackEquipmentDetailEntity.setReturnEquipmentId(cbsReturnEquipmentEntity);
                    cbsBackEquipmentDetailEntity.setReturnEquipmentDetailId(cbsReturnEquipmentDetailEntity);
                    cbsBackEquipmentDetailEntity.setVerCode(verCode);
                    cbsBackEquipmentDetailEntity.setSn(sn);
                    cbsBackEquipmentDetailEntity.setWarehouseId(warehouse);
                    cbsBackEquipmentDetailEntity.setWarehousePosition(warehousePosition);
                    if (itemEntity != null) {
                        cbsBackEquipmentDetailEntity.setItemId(itemEntity);
                        cbsBackEquipmentDetailEntity.setItem(itemEntity.getItem());
                    } else {
                        cbsBackEquipmentDetailEntity.setItemId(null);
                        cbsBackEquipmentDetailEntity.setItem(itemIn);
                    }
                    cbsBackEquipmentDetailEntity.setEquipmentErcode(equipmentErcode);
                    cbsBackEquipmentDetailEntity.setMemo(memo);
                    cbsBackEquipmentDetailEntity.setMatterNum(matterNum);
                    cbsBackEquipmentDetailEntity.setOpenCheck(openCheck);
                    systemService.saveOrUpdate(cbsBackEquipmentDetailEntity);

                    //开箱检查创建异常记录
                    if (StringUtil.isNotEmpty(openCheck) && !openCheck.equals(StaticValue.open_zc)) {
                        CbsBackErrorLogEntity cbsBackErrorLogEntity = new CbsBackErrorLogEntity();
                        cbsBackErrorLogEntity.setDescription("入库开箱检查异常");
                        cbsBackErrorLogEntity.setCbsReturnId(cbsReturnEquipmentDetailEntity.getReturnEquipmentId()); //返件id
                        cbsBackErrorLogEntity.setCbsReturnDetailId(cbsReturnEquipmentDetailEntity); //返件明细Id
                        cbsBackErrorLogEntity.setIsClose(1);
                        systemService.saveOrUpdate(cbsBackErrorLogEntity);
                    }

                }
            }

        }


        return ajaxJson;
    }

    /**
     * 工程师返件入库
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "doReturnEquipmentGCS")
    public AjaxJson doReturnEquipmentGCS(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        boolean flag = true;
        String messag = "工程师返件成功";
        String returnId = request.getParameter("returnId");
        /*返件主表*/
        CbsReturnEquipmentEntity cbsReturnEquipmentEntity = null;
        String list = request.getParameter("datalist");

        if (StringUtil.isNotEmpty(returnId)) {
            cbsReturnEquipmentEntity = systemService.get(CbsReturnEquipmentEntity.class, returnId);
            if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity)) {
                if (cbsReturnEquipmentEntity.getStatus().equals(StaticValue.RETURN_STATUS_Log_Type_1)) {

                    cbsReturnEquipmentEntity.setName(request.getParameter("name"));
                    cbsReturnEquipmentEntity.setPhone(request.getParameter("phone"));
                    cbsReturnEquipmentEntity.setAddress(request.getParameter("address"));
                    cbsReturnEquipmentEntity.setCinemaName(request.getParameter("cinemaName"));
                    cbsReturnEquipmentEntity.setStatus(StaticValue.RETURN_STATUS_Log_Type_2); //返件状态为返件中
                    String shengId = request.getParameter("sheng");
                    String shiId = request.getParameter("shi");
                    if (StringUtil.isNotEmpty(shengId)) {
                        TSTerritory sheng = systemService.get(TSTerritory.class, shengId);
                        if (sheng != null) {
                            cbsReturnEquipmentEntity.setSheng(sheng);
                        }
                    }
                    if (StringUtil.isNotEmpty(shiId)) {
                        TSTerritory shi = systemService.get(TSTerritory.class, shiId);
                        if (shi != null) {
                            cbsReturnEquipmentEntity.setShi(shi);
                        }
                    }
                    cbsReturnEquipmentEntity.setNoticeReturnTime(new Date());
                    systemService.saveOrUpdate(cbsReturnEquipmentEntity);

                    JSONArray jsonArray = JSONArray.fromObject(list);
                    for (Object o : jsonArray) {
                        JSONObject jso = JSONObject.fromObject(o);
                        String id = jso.get("rd").toString();
                        String fileId = jso.get("photoName").toString();
                        ZyFileLogEntity photoFile = systemService.get(ZyFileLogEntity.class, fileId);
                        if (StringUtil.isNotEmpty(id)) {
                            /*返件详情表*/
                            CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity = systemService.get(CbsReturnEquipmentDetailEntity.class, id);
                            cbsReturnEquipmentDetailEntity.setReturnEquipmentStatus(jso.get("returnEquipmentStatus").toString()); //返件状态
                            String typeId = jso.get("typeDesc").toString();
                            if (typeId != null && !typeId.equals("")) {
                                ZyEquipmentTypeEntity type = systemService.get(ZyEquipmentTypeEntity.class, typeId);
                                if (type != null) {
                                    cbsReturnEquipmentDetailEntity.setTypeId(type);
                                    cbsReturnEquipmentDetailEntity.setTypeDes(type.getTypeDesc());
                                }
                            }

                            String itemId = jso.get("item").toString();
                            String itemIn = jso.get("itemIn").toString();
                            if (itemId != null && !itemId.equals("")) {
                                ZyEsItemEntity item = systemService.get(ZyEsItemEntity.class, itemId);
                                if (item != null) {
                                    cbsReturnEquipmentDetailEntity.setItemId(item);
                                    cbsReturnEquipmentDetailEntity.setItem(item.getItem());
                                }
                            } else {
                                cbsReturnEquipmentDetailEntity.setItemId(null);
                                cbsReturnEquipmentDetailEntity.setItem(itemIn);
                            }
                            cbsReturnEquipmentDetailEntity.setEquipmentErcode(jso.get("equipmentErcode").toString());
                            cbsReturnEquipmentDetailEntity.setSn(jso.get("sn").toString());
                            cbsReturnEquipmentDetailEntity.setMemo(jso.get("memo").toString());
                            if (photoFile != null) {
                                cbsReturnEquipmentDetailEntity.setPhotoName(photoFile.getOldFileName());
                                cbsReturnEquipmentDetailEntity.setFilePath(photoFile.getFilePath());
                            }
                            systemService.saveOrUpdate(cbsReturnEquipmentDetailEntity);

                        }
                    }


                    /*通知返件后24小时（该时限可人为设置）后该返件任务状态依然为“返件中”，短信提醒物流商务联系人*/
                    if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity)) {
                        returnEquimentStatus(cbsReturnEquipmentEntity.getId());
                    }

                    //记录操作日志
                    TSUser user = ResourceUtil.getSessionUserName();
                    CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                    cbsHandleLogEntity.setBusinessId(cbsReturnEquipmentEntity.getId());
                    cbsHandleLogEntity.setLogType(4);
                    cbsHandleLogEntity.setDescription("工程师通知返件");
                    cbsHandleLogEntity.setCreateName(user.getRealName());
                    cbsHandleLogEntity.setCreateBy(user.getUserName());
                    systemService.saveOrUpdate(cbsHandleLogEntity);

                    //获取影院名称
                    String cinemaName = "";
                    List<CbsDelinerEntity> CbsDelinerEntitys = systemService.findHql("from CbsDelinerEntity where code = '" + cbsReturnEquipmentEntity.getDeliverCode() + "'");
                    if (CbsDelinerEntitys.size() > 0) {
                        cinemaName = CbsDelinerEntitys.get(0).getCinemaName();
                    }

                    /*工程师提交返件后邮件和短信以及APP信息  给物流联系人*/
                    if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity)) {
                        String logistics = cbsReturnEquipmentEntity.getLogistics();  //物流单号
                        if (StringUtil.isNotEmpty(logistics)) {
                            String hql = "from TSDepart where departname = '" + logistics + "' and orgType='logistics'";
                            TSDepart tsDepart = systemService.singleResult(hql);
                            List<ZyContactsEntity> zyContactsEntities = systemService.findHql("from ZyContactsEntity where belongOrg.id = '" + tsDepart.getId() + "'");
                            if (zyContactsEntities != null && zyContactsEntities.size() > 0) {

                                for (ZyContactsEntity zyContactsEntity : zyContactsEntities) {
                                    //18/5/17   修改取物流联系人为在职的物流联系人
                                    if (zyContactsEntity.getState().equals(StaticValue.DIC_ENGINEER_STATE_ONJOB)) {
                                        TSUser tsUser = ResourceUtil.getSessionUserName(); //当前人id

                                        /*邮件*/
                                        ZyEmailEntity eMail = new ZyEmailEntity();
                                        SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                                        String s = "返件通知：<" + cbsReturnEquipmentEntity.getCode() + ">-<" + cbsReturnEquipmentEntity.getCrCode() + ">-<" + cinemaName + ">-<" + cbsReturnEquipmentEntity.getSoCode() + ">-" + sdf.format(new Date()) + "";
                                        eMail.setEmailSubject(s);
                                        eMail.setEmailReceiver(zyContactsEntity.getEmail());
                                        Map<String, Object> paraMap1 = new HashMap<String, Object>();
                                        paraMap1.put("code", cbsReturnEquipmentEntity.getCode());
                                        paraMap1.put("zyContactsName", tsUser.getRealName());
                                        paraMap1.put("phone", tsUser.getMobilePhone());
                                        SendMailUtil.sendFtlMail(eMail, "mail_back_service.ftl", paraMap1, systemService);


                                        /*短信*/
                                        Map<String, Object> paraMap = new HashMap<String, Object>();
                                        paraMap.put("code", cbsReturnEquipmentEntity.getCode());
                                        paraMap.put("zyContactsName", tsUser.getRealName());
                                        paraMap.put("phone", tsUser.getMobilePhone());
                                        SendMessage.sendSMSFTL(zyContactsEntity.getCellphone1(), "message_back_service.ftl", paraMap, systemService);

                                    }
                                }
                            }
                        }
                    }
                } else {
                    flag = false;
                    messag = "返件状态已改变，请刷新页面后再操作";
                }
            }
        }
        ajaxJson.setMsg(messag);
        ajaxJson.setSuccess(flag);
        return ajaxJson;
    }

    /**
     * 提交返件预约
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "submitReturnEquipment")
    public AjaxJson submitReturnEquipment(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = req.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
            /*返件信息*/
            CbsReturnEquipmentEntity cbsReturnEquipmentEntity = systemService.get(CbsReturnEquipmentEntity.class, id);
            if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity)) {
                cbsReturnEquipmentEntity.setBackwarehouseTime(req.getParameter("backwarehouseTime"));
                cbsReturnEquipmentEntity.setPickupTime(req.getParameter("expectTime")); //yu ji dao huo time
                cbsReturnEquipmentEntity.setLogisticsCode(req.getParameter("code")); //
                cbsReturnEquipmentEntity.setLogisticsMemo(req.getParameter("logisticsMemo"));
                cbsReturnEquipmentEntity.setStatus(StaticValue.RETURN_STATUS_Log_Type_3);
                cbsReturnEquipmentService.saveOrUpdate(cbsReturnEquipmentEntity);

                TSUser user = ResourceUtil.getSessionUserName();
                CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                //预计取货时间log();
                cbsHandleLogEntity.setBusinessId(cbsReturnEquipmentEntity.getId());
                cbsHandleLogEntity.setLogType(4);
                cbsHandleLogEntity.setDescription("预计取件时间：" + req.getParameter("expectTime"));
                cbsHandleLogEntity.setCreateName(user.getRealName());
                cbsHandleLogEntity.setCreateBy(user.getUserName());
                systemService.saveOrUpdate(cbsHandleLogEntity);
            }

            List<CbsReturnEquipmentDetailEntity> cbsReturnEquipmentDetailEntities = systemService.findByProperty(CbsReturnEquipmentDetailEntity.class, "returnEquipmentId.id", id);
            if (cbsReturnEquipmentDetailEntities.size() > 0) {
                for (CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity : cbsReturnEquipmentDetailEntities) {
                    List<CbsBackEquipmentDetailEntity> cbsBackEquipmentDetailEntities = systemService.findByProperty(CbsBackEquipmentDetailEntity.class, "returnEquipmentDetailId.id", cbsReturnEquipmentDetailEntity.getId());
                    if (cbsBackEquipmentDetailEntities.size() == 0) {
                        CbsBackEquipmentDetailEntity cbsBackEquipmentDetailEntity = new CbsBackEquipmentDetailEntity();
                        cbsBackEquipmentDetailEntity.setReturnEquipmentId(cbsReturnEquipmentEntity);
                        cbsBackEquipmentDetailEntity.setReturnEquipmentDetailId(cbsReturnEquipmentDetailEntity);
                        systemService.saveOrUpdate(cbsBackEquipmentDetailEntity);
                    }
                }
            }
            
            //Add start Amy 181113 增加向取货联系人发送微信消息
            List<Map<String, String>> list = new ArrayList<>();
            if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity)) {
                String content = "尊敬的客户：您的服务单<" + cbsReturnEquipmentEntity.getCrCode() + ">所涉及的备件，预计在<" + req.getParameter("expectTime") + ">安排物流人员取回。请您妥善保管备件，感谢您的配合。【中影巴可客服部】";
                if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity.getPhone().trim())) {
                    List<TSUser> user1 = systemService.findByProperty(TSUser.class, "mobilePhone", cbsReturnEquipmentEntity.getPhone().trim());
                    if (user1 != null && user1.size() > 0) {
                        if (StringUtil.isNotEmpty(user1.get(0).getOpenId())) {
                            Map<String, String> mapwx = new HashMap<>();
                            mapwx.put("openid", user1.get(0).getOpenId());
                            mapwx.put("message", content);
                            list.add(mapwx);
                            try {
								wxCommonService.sendMsgForWx(list);
							} catch (Exception e) {
								e.printStackTrace();
							}
                        }
                    }
                }
            }

            //Add end Amy 181113 
        }


        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "doCompareTime")
    public AjaxJson doCompareTime(HttpServletRequest req) throws ParseException {
        AjaxJson ajaxJson = new AjaxJson();
        Date date = new Date();
        String id = req.getParameter("id");
        CbsReturnEquipmentEntity cbsReturnEquipmentEntity = systemService.get(CbsReturnEquipmentEntity.class, id);
        if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity)) {
            if (!cbsReturnEquipmentEntity.getStatus().equals(StaticValue.RETURN_STATUS_Log_Type_4) && !cbsReturnEquipmentEntity.getStatus().equals(StaticValue.RETURN_STATUS_Log_Type_5)) {
                String backTime = cbsReturnEquipmentEntity.getBackwarehouseTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date backDate = simpleDateFormat.parse(backTime);
                long l = backDate.getTime() - date.getTime();
                //long l = DateUtils.timeDifference(simpleDateFormat.format(date),backTime);
                if (l > 0) {
                    ajaxJson.setSuccess(true);
                    ajaxJson.setMsg("备件已入库");
                } else {
                    ajaxJson.setSuccess(false);
                }
            } else {
                ajaxJson.setSuccess(true);
                ajaxJson.setMsg("ERROR");
            }
        }

        return ajaxJson;
    }

    /**
     * 取消返件
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "doSureCandel")
    public AjaxJson doSureCandel(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = req.getParameter("id");
        String candelDes = req.getParameter("candelDes");
        String status = "";
        CbsReturnEquipmentEntity cbsReturnEquipmentEntity = systemService.get(CbsReturnEquipmentEntity.class, id);
        if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity)) {
            status = cbsReturnEquipmentEntity.getStatus();
            cbsReturnEquipmentEntity.setCandelDes(candelDes);
            cbsReturnEquipmentEntity.setStatus(StaticValue.RETURN_STATUS_Log_Type_5);
            systemService.saveOrUpdate(cbsReturnEquipmentEntity);


            //记录操作日志
            TSUser user = ResourceUtil.getSessionUserName();
            CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
            cbsHandleLogEntity.setBusinessId(cbsReturnEquipmentEntity.getId());
            cbsHandleLogEntity.setLogType(4);
            cbsHandleLogEntity.setDescription("取消返件");
            cbsHandleLogEntity.setCreateName(user.getRealName());
            cbsHandleLogEntity.setCreateBy(user.getUserName());
            systemService.saveOrUpdate(cbsHandleLogEntity);

            //获取影院名称
            String cinemaName = "";
            List<CbsDelinerEntity> CbsDelinerEntitys = systemService.findHql("from CbsDelinerEntity where code = '" + cbsReturnEquipmentEntity.getDeliverCode() + "'");
            if (CbsDelinerEntitys.size() > 0) {
                cinemaName = CbsDelinerEntitys.get(0).getCinemaName();
            }
            //发送邮件 CSA取消返件
            if (status.equals(StaticValue.RETURN_STATUS_Log_Type_1) || status.equals(StaticValue.RETURN_STATUS_Log_Type_2) || status.equals(StaticValue.RETURN_STATUS_Log_Type_3)) {
                //当前人id
                TSUser tsUser = ResourceUtil.getSessionUserName();
                String logistics = cbsReturnEquipmentEntity.getLogistics();  //物流单号
                if (StringUtil.isNotEmpty(logistics)) {
                    String hql = "from TSDepart where departname = '" + logistics + "' and orgType='" + StaticValue.CBS_WL_ROLE_CODE + "'";
                    TSDepart tsDepart = systemService.singleResult(hql);
                    List<ZyContactsEntity> zyContactsEntities = systemService.findHql("from ZyContactsEntity where belongOrg.id = '" + tsDepart.getId() + "'");
                    if (zyContactsEntities != null && zyContactsEntities.size() > 0) {
                        for (ZyContactsEntity contactsEntity : zyContactsEntities) {
                            if (contactsEntity.getState().equals(StaticValue.DIC_ENGINEER_STATE_ONJOB)) {
                                /*邮件*/
                                ZyEmailEntity eMail = new ZyEmailEntity();
                                SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                                String s = "取消返件通知：" + cbsReturnEquipmentEntity.getCode() + "-" + cbsReturnEquipmentEntity.getCrCode() + "-" + cinemaName + "-" + cbsReturnEquipmentEntity.getSoCode() + "-" + sdf.format(new Date()) + "";
                                eMail.setEmailSubject(s);
                                eMail.setEmailReceiver(contactsEntity.getEmail());
                                Map<String, Object> paraMap1 = new HashMap<String, Object>();
                                paraMap1.put("code", cbsReturnEquipmentEntity.getCode());
                                paraMap1.put("candelDes", candelDes);
                                paraMap1.put("name", tsUser.getRealName());
                                paraMap1.put("phone", tsUser.getMobilePhone());
                                SendMailUtil.sendFtlMail(eMail, "mail_candel_service.ftl", paraMap1, systemService);
                                SendMessage.sendSMSFTL(contactsEntity.getCellphone1(), "message_candel_service.ftl", paraMap1, systemService);
                            }
                        }
                    }
                }
            }
        }

        return ajaxJson;
    }

    /**
     * 返件主表信息新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsReturnEquipmentEntity cbsReturnEquipment, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsReturnEquipment.getId())) {
            cbsReturnEquipment = cbsReturnEquipmentService.getEntity(CbsReturnEquipmentEntity.class, cbsReturnEquipment.getId());
            req.setAttribute("cbsReturnEquipmentPage", cbsReturnEquipment);
        }
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipment-add");
    }

    /**
     * 返件详情查看页面
     *
     * @return
     */
    @RequestMapping(params = "detailesForAll")
    public ModelAndView detailesForAll(HttpServletRequest req) {
        String id = req.getParameter("id");
        String type = req.getParameter("type");
        req.setAttribute("type", type);
        System.out.println("id:" + id);
        if (StringUtil.isNotEmpty(id)) {
            req.setAttribute("id", id);
            /*关联信息*/
            CbsReturnEquipmentEntity cbsReturnEquipment = cbsReturnEquipmentService.getEntity(CbsReturnEquipmentEntity.class, id);
            if (StringUtil.isNotEmpty(cbsReturnEquipment)) {
                req.setAttribute("cbsReturnEquipmentPage", cbsReturnEquipment);

                //根据返件获取发货单的省市,2018/7/18
                String sql = "SELECT t.territoryname as tesheng, t1.territoryname as teshi FROM `cbs_return_equipment` e LEFT JOIN cbs_deliver d ON d.`code` = e.deliver_code LEFT JOIN t_s_territory t ON d.sheng = t.ID LEFT JOIN t_s_territory t1 ON d.shi = t1.ID WHERE 1 = 1 AND e.deliver_code = '" + cbsReturnEquipment.getDeliverCode() + "' LIMIT 0, 1";
                List<Map<String, Object>> ssmap = systemService.findForJdbc(sql);
                String tesheng = "";
                String teshi = "";
                if (ssmap.size() > 0) {
                    if (StringUtil.isNotEmpty(ssmap.get(0))) {
                        if (StringUtil.isNotEmpty(ssmap.get(0).get("tesheng"))) {
                            tesheng = ssmap.get(0).get("tesheng").toString();
                        }
                        if (StringUtil.isNotEmpty(ssmap.get(0).get("teshi"))) {
                            teshi = ssmap.get(0).get("teshi").toString();
                        }
                    }
                }
                req.setAttribute("tesheng", tesheng);
                req.setAttribute("teshi", teshi);

                //返件状态
                List<TSType> status = systemService.findHql("from TSType where TSTypegroup.typegroupcode='return_status' and typecode='" + cbsReturnEquipment.getStatus() + "'");
                if (status != null && status.size() > 0) {
                    req.setAttribute("status", status.get(0).getTypename());
                }
                /*取货联系人信息*/
                List<CbsDelinerEntity> cbsDelinerEntities = systemService.findByProperty(CbsDelinerEntity.class, "code", cbsReturnEquipment.getDeliverCode());
                if (cbsDelinerEntities.size() > 0) {
                    req.setAttribute("cbsDelinerEntities", cbsDelinerEntities.get(0));
                }
                //返件物流信息
//                String logisticsCode = cbsReturnEquipment.getLogisticsCode();//返件物流编号
//                String hql = "from TSDepart where org_code = '" + logisticsCode + "'";
//                TSDepart tsDepart = systemService.singleResult(hql);
//                req.setAttribute("tsDepart",tsDepart);

//                List<TSUserOrg> tsUserOrgs = systemService.findHql("from TSUserOrg where tsDepart.id = '" + tsDepart.getId() + "'");
//                if(tsUserOrgs.size()>0){
//                    TSUserOrg userOrg = tsUserOrgs.get(0);
//                    if(StringUtil.isNotEmpty(userOrg))
//                    req.setAttribute("tsUser", userOrg.getTsUser());
//                }

                //返件入库照片
                List<ZyFileLogEntity> backFileList = systemService.findHql("from ZyFileLogEntity where businessKey='" + id + "' and businessType='H'");
                req.setAttribute("backFileList", backFileList);
                //返件详情照片
                List<ZyFileLogEntity> detailFileList = systemService.findHql("from ZyFileLogEntity where businessType='E'");
//                List<ZyFileLogEntity> detailFileList = systemService.findHql("from ZyFileLogEntity where businessKey='" + id + "' and businessType='E'");
                req.setAttribute("detailFileList", detailFileList);
            }
            /*返件信息*/
            List<CbsReturnEquipmentDetailEntity> cbsReturnEquipmentDetailEntities = systemService.findByProperty(CbsReturnEquipmentDetailEntity.class, "returnEquipmentId.id", id);
            if (cbsReturnEquipmentDetailEntities.size() > 0) {
                req.setAttribute("cbsReturnEquipmentDetailEntities", cbsReturnEquipmentDetailEntities);
            }
            /*入库信息*/
            List<CbsBackEquipmentDetailEntity> cbsBackEquipmentDetailEntities = systemService.findByProperty(CbsBackEquipmentDetailEntity.class, "returnEquipmentId.id", id);
            if (cbsBackEquipmentDetailEntities.size() > 0) {
                req.setAttribute("cbsBackEquipmentDetailEntities", cbsBackEquipmentDetailEntities);
            }

            //查询所有物流
            List<TSDepart> logList = systemService.findHql("from TSDepart where orgType='logistics' and logicDelete = '0'");
            req.setAttribute("logisticsList", logList);

            //查询所有开箱检查结果
            List<TSType> openCheckList = systemService.findHql("from TSType where TSTypegroup.typegroupcode='open_check'");
            req.setAttribute("openCheckList", openCheckList);
            /*返件日志*/
            List<CbsHandleLogEntity> cbsHandleLogEntities = systemService.findHql("from CbsHandleLogEntity where logType=4 and businessId='" + id + "' ORDER BY createDate DESC");
            req.setAttribute("cbsHandleLogEntities", cbsHandleLogEntities);
        }
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipment_detailesForAll");
    }

    /**
     * 添加返件主表信息
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsReturnEquipmentEntity cbsReturnEquipment, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "返件主表信息添加成功";
        try {
            cbsReturnEquipmentService.save(cbsReturnEquipment);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "返件主表信息添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 返件主表信息编辑页面跳转
     *
     * @return
     */
//    @RequestMapping(params = "goUpdate")
//    public ModelAndView goUpdate(CbsReturnEquipmentEntity cbsReturnEquipment, HttpServletRequest req) {
//        if (StringUtil.isNotEmpty(cbsReturnEquipment.getId())) {
//            cbsReturnEquipment = cbsReturnEquipmentService.getEntity(CbsReturnEquipmentEntity.class, cbsReturnEquipment.getId());
//            req.setAttribute("cbsReturnEquipmentPage", cbsReturnEquipment);
//        }
//        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipment-update");
//    }

    /**
     * 更新返件主表信息
     *
     * @param
     * @return
     */
//    @RequestMapping(params = "doUpdate")
//    @ResponseBody
//    public AjaxJson doUpdate(CbsReturnEquipmentEntity cbsReturnEquipment, HttpServletRequest request) {
//        AjaxJson j = new AjaxJson();
//        message = "返件主表信息更新成功";
//        CbsReturnEquipmentEntity t = cbsReturnEquipmentService.get(CbsReturnEquipmentEntity.class, cbsReturnEquipment.getId());
//        try {
//            MyBeanUtils.copyBeanNotNull2Bean(cbsReturnEquipment, t);
//            cbsReturnEquipmentService.saveOrUpdate(t);
//            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
//        } catch (Exception e) {
//            e.printStackTrace();
//            message = "返件主表信息更新失败";
//            throw new BusinessException(e.getMessage());
//        }
//        j.setMsg(message);
//        return j;
//    }


    /**
     * 删除返件主表信息
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsReturnEquipmentEntity cbsReturnEquipment, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsReturnEquipment = systemService.getEntity(CbsReturnEquipmentEntity.class, cbsReturnEquipment.getId());
        message = "返件主表信息删除成功";
        try {
            cbsReturnEquipmentService.delete(cbsReturnEquipment);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "返件主表信息删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除返件主表信息
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "返件主表信息删除成功";
        try {
            for (String id : ids.split(",")) {
                CbsReturnEquipmentEntity cbsReturnEquipment = systemService.getEntity(CbsReturnEquipmentEntity.class,
                        id
                );
                cbsReturnEquipmentService.delete(cbsReturnEquipment);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "返件主表信息删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipmentUpload");
    }

    @RequestMapping(params = "exportXls1")
    public void exportXls1(HttpServletRequest request, HttpServletResponse response) {

        cbsReturnEquipmentService.exportReturnList(request, response);

    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsReturnEquipmentEntity cbsReturnEquipment, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(TemplateExcelConstants.FILE_NAME, "返件主表信息");
        modelMap.put(TemplateExcelConstants.PARAMS, new TemplateExportParams("Excel模板地址"));
        modelMap.put(TemplateExcelConstants.MAP_DATA, null);
        modelMap.put(TemplateExcelConstants.CLASS, CbsReturnEquipmentEntity.class);
        modelMap.put(TemplateExcelConstants.LIST_DATA, null);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CbsReturnEquipmentEntity> listCbsReturnEquipmentEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(), CbsReturnEquipmentEntity.class, params);
                for (CbsReturnEquipmentEntity cbsReturnEquipment : listCbsReturnEquipmentEntitys) {
                    cbsReturnEquipmentService.save(cbsReturnEquipment);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

    /**
     * 返件异常列表
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "CbsReturnEquipmentError")
    public ModelAndView CbsReturnEquipmentError(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipmentErrorList");
    }


    @RequestMapping(params = "errorDatagrid")
    public void errorDatagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        try {
            Map param = new HashMap<>();
            boolean flag = false; //页面查询条件为空时不做查询
    		Map<String, String[]> parameterMap = request.getParameterMap();
            for (String key : parameterMap.keySet()) {
                if (key.equals("code") || key.equals("isClose") || key.equals("needSystemRevise") ||
                		 key.equals("createDate_begin") || key.equals("createDate_end")) {
                    if (!StringUtil.isEmpty(parameterMap.get(key)[0])) {
                        flag = true;//页面 查询条件为空不做查询
                        break;
                    }
                }
            }
            if (flag) {
	            for (Object key : request.getParameterMap().keySet()) {
	                if ((String[]) request.getParameterMap().get(key) != null) {
	                    for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
	                        if (((String[]) request.getParameterMap().get(key))[i] != null) {
	                            param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
	                        }
	                    }
	                }
	            }
	            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_begin")))) {
	                param.put("createDate_begin", oConvertUtils.getString(param.get("createDate_begin")) + " 00:00:00");
	            }
	            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_end")))) {
	                param.put("createDate_end", oConvertUtils.getString(param.get("createDate_end")) + " 23:59:59");
	            } 
            }else {
            	param.put("isClose", 1);
            }

            wiseCoreService.selectDataGrid("getReturnErrorLogList", param, dataGrid);

        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }


        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * 返件异常记录表编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(HttpServletRequest req) {
        if (StringUtil.isNotEmpty(req.getParameter("id"))) {
            CbsBackErrorLogEntity cbsBackErrorLog = systemService.getEntity(CbsBackErrorLogEntity.class, req.getParameter("id"));
            req.setAttribute("cbsBackErrorLog", cbsBackErrorLog);
        }

        boolean flag = false;
        TSUser user = ResourceUtil.getSessionUserName();
        List<Map<String, Object>> roleList = systemService.findForJdbc("SELECT * FROM t_s_role r LEFT JOIN t_s_role_user u ON r.id = u.roleid where u.userid = '" + user.getId() + "';");
        if (StringUtil.isNotEmpty(roleList)) {
            if (roleList.size() > 0) {
                String num = (String) roleList.get(0).get("rolecode");
                if (num.equals(StaticValue.ROLE_CODE_ADMIN)) {
                    flag = true;
                }
            }
        }

        if (flag) {
            return new ModelAndView("com/zybk/cbs_return_equipment/cbsBackErrorLog-adminUpdate");
        } else {
            return new ModelAndView("com/zybk/cbs_return_equipment/cbsBackErrorLog-update");

        }
    }

    /**
     * 更新返件异常记录表
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsBackErrorLogEntity cbsBackErrorLog, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "返件异常记录更新成功";
        String id = cbsBackErrorLog.getId();
        if (StringUtil.isNotEmpty(id)) {
            String description = cbsBackErrorLog.getHandleDescription();
            String abnormalResult = cbsBackErrorLog.getAbnormalResult();
            TSUser user = ResourceUtil.getSessionUserName();
            CbsBackErrorLogEntity cbsServiceErrorLog = systemService.getEntity(CbsBackErrorLogEntity.class, cbsBackErrorLog.getId());
            try {
                //判断角色是否是管理员
                boolean flag = false;
                List<Map<String, Object>> roleList = systemService.findForJdbc("SELECT * FROM t_s_role r LEFT JOIN t_s_role_user u ON r.id = u.roleid where u.userid = '" + user.getId() + "';");
                if (StringUtil.isNotEmpty(roleList)) {
                    if (roleList.size() > 0) {
                        String num = (String) roleList.get(0).get("rolecode");
                        if (num.equals(StaticValue.ROLE_CODE_ADMIN)) {
                            flag = true;  //是管理员
                        }
                    }
                }
                if (flag) {
                    cbsServiceErrorLog.setAdminAbnormalResult(cbsBackErrorLog.getAdminAbnormalResult());
                    cbsServiceErrorLog.setAdminDescription(cbsBackErrorLog.getAdminDescription());
                    cbsServiceErrorLog.setAdminUpdateDate(new Date());
                    cbsServiceErrorLog.setAdminUpdateBy(user.getRealName());
                    cbsServiceErrorLog.setNeedSystemRevise("1");
                } else {
                    cbsServiceErrorLog.setHandleDescription(description);
                    cbsServiceErrorLog.setAbnormalResult(abnormalResult);
                    cbsServiceErrorLog.setUpdateDate(new Date());
                    cbsServiceErrorLog.setUpdateName(user.getUserName());
                    cbsServiceErrorLog.setUpdateBy(user.getRealName());
                    cbsServiceErrorLog.setNeedSystemRevise("2");
                }
                cbsServiceErrorLog.setIsClose(StaticValue.service_ERROR_Log_Type_2);
                systemService.saveOrUpdate(cbsServiceErrorLog);
                if (flag) {
                    systemService.updateBySqlString("update CBS_BACK_ERROR_LOG set update_name='',update_date=null where id = '" + cbsBackErrorLog.getId() + "'");
                }
                systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
            } catch (Exception e) {
                e.printStackTrace();
                message = "返件异常记录更新失败";
                throw new BusinessException(e.getMessage());
            }
            j.setMsg(message);
        }

        return j;
    }


    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public void exportXls(HttpServletRequest request, HttpServletResponse response) {
        TSUser user = ResourceUtil.getSessionUserName();
        OutputStream out = null;
        try {
            String fileName = "返件异常.xlsx";
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + (new String(fileName.getBytes("gb2312"), "ISO8859-1")));
            out = response.getOutputStream();
            String[] planIdsArr = oConvertUtils.getString(request.getParameter("planIds")).split(",");
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT\n" +
                    "\tl.id AS id,\n" +
                    "\tIFNULL(l.create_date, '') AS createDate,\n" +
                    "\tIFNULL(cbs.`code`, '') AS `code`,\n" +
                    "\tCASE l.is_close\n" +
                    "WHEN '1' THEN\n" +
                    "\t'未处理'\n" +
                    "WHEN '2' THEN\n" +
                    "\t'已处理'\n" +
                    "ELSE\n" +
                    "\t''\n" +
                    "END AS isClose,\n" +
                    "\tIFNULL(l.description, '') AS description,\n" +
                    "\tIFNULL(l.handle_description, '') AS handleDescription,\n" +
                    " IFNULL(l.update_by, '') AS updateBy,\n" +
                    " IFNULL(l.update_date, '') AS updateDate,\n" +
                    " IFNULL(l.abnormal_result, '') AS abnormalResult,\n" +
                    " CASE l.need_system_revise WHEN '1' then '是' WHEN '2' then '否' END AS needSystemRevise,\n" +
                    " IFNULL(l.admin_description, '') AS adminDescription,\n" +
                    " IFNULL(l.admin_updateBy, '') AS adminUpdateBy,\n" +
                    " IFNULL(l.admin_updateDate, '') AS adminUpdateDate,\n" +
                    " IFNULL(l.admin_abnormal_result, '') AS adminAbnormalResult\n" +
                    "FROM\n" +
                    "\tCBS_BACK_ERROR_LOG l\n" +
                    "LEFT JOIN cbs_return_equipment cbs ON cbs.id = l.CBS_RETURN_ID\n" +
                    "LEFT JOIN cbs_return_equipment_detail eq ON eq.RETURN_EQUIPMENT_ID = cbs.id\n" +
                    "WHERE  ");
            sql.append(" l.id IN ( ");
            for (int i = 0; i < planIdsArr.length; i++) {
                if (i == planIdsArr.length - 1) {
                    sql.append("'" + planIdsArr[i] + "'");
                } else {
                    sql.append("'" + planIdsArr[i] + "',");
                }
            }
            sql.append(" 	) ");
            sql.append("GROUP BY l.id");
            List<Map<String, Object>> reusltMaps = systemService.findForJdbc(sql.toString());
            systemService.addLog(user.getRealName() + "导出" + reusltMaps.size() + "条备件申请单记录", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);

            InputStream is = ZyInspectionPlanServiceImpl.class.getClassLoader().getResourceAsStream("jeecg/template/backErrorexportXLS.xlsx");
            XSSFWorkbook xssf = new XSSFWorkbook(is);
            XSSFSheet sheet = xssf.getSheetAt(0);
            int rowNum = 1;
            for (Map<String, Object> dataMap : reusltMaps) {
                XSSFRow row = sheet.createRow(rowNum);
                int cellNum = 0, index = 0;
                for (String key : dataMap.keySet()) {
                    if (index == 0) {
                        index++;
                        continue;
                    }
                    XSSFCell cell = row.createCell(cellNum);
                    cell.setCellValue(dataMap.get(key) != null ? dataMap.get(key).toString() : "");
                    cellNum++;
                }
                rowNum++;
            }
            xssf.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @RequestMapping(params = "getImgFile")
    @ResponseBody
    public AjaxJson getImgFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String businessKey = request.getParameter("businessKey");
        List<Object[]> files = systemService.findListbySql("select id from zy_file_log where business_type='E' and business_key='" + businessKey + "' ORDER BY create_date desc;");
        j.setObj(files);
        return j;
    }

    @RequestMapping(params = "getBackImgFile")
    @ResponseBody
    public AjaxJson getBackImgFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String businessKey = request.getParameter("businessKey");
        List<Object[]> files = systemService.findListbySql("select id from zy_file_log where business_type='H' and business_key='" + businessKey + "' ORDER BY create_date desc;");
        j.setObj(files);
        return j;
    }


    @RequestMapping(params = "getItmById")
    @ResponseBody
    public AjaxJson getItmById(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String id = request.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
            ZyEsItemEntity itemEntity = systemService.get(ZyEsItemEntity.class, id);
            j.setObj(itemEntity);
        }
        return j;
    }

    @ResponseBody
    @RequestMapping(params = "getCity")
    public AjaxJson getCity(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = request.getParameter("id");
        List<TSTerritory> territoryList = null;
        territoryList = systemService.findHql("from TSTerritory  where  territorylevel = '2' and TSTerritory.id='" + id + "'");
        ajaxJson.setObj(territoryList);
        return ajaxJson;
    }
}
